package com.jindouyun.provider.service;

import com.jindouyun.api.model.user.dto.UserQueryDTO;
import com.jindouyun.api.model.user.vo.UserQueryVO;
import com.jindouyun.api.service.user.IUserService;
import com.jindouyun.common.annotations.JDYService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @className: com.jindouyun.provider.service.UserServiceImpl
 * @description: 用户业务逻辑实现类
 * @author: tong.li
 * @createTime: 2021/10/12 17:48
 * @copyright: Tongcheng-Elong Holdings Limited
 */
@Service
/** @JDYService标记这是一个筋斗云RPC的服务类 */
@JDYService
public class UserServiceImpl implements IUserService {

    /** 模拟存放数据库表的所有记录 */
    private static List<UserQueryVO> records = null;

    /**
     * 类加载时初始化用户数据
     */
    static {
        records = new ArrayList<>();
        records.add(UserQueryVO.builder().id(1L).name("张三").age((byte) 28).city("上海市").build());
        records.add(UserQueryVO.builder().id(2L).name("李四").age((byte) 21).city("北京市").build());
        records.add(UserQueryVO.builder().id(9L).name("王五").age((byte) 25).city("西安市").build());
        records.add(UserQueryVO.builder().id(4L).name("赵六").age((byte) 36).city("成都市").build());
        records.add(UserQueryVO.builder().id(5L).name("李六六").age((byte) 36).city("昆明市").build());
    }

    @Override
    public List<UserQueryVO> queryUsersByConditions(UserQueryDTO userQuery) {
        Long id = userQuery.getId();
        String name = userQuery.getName();
        Byte age = userQuery.getAge();
        String city = userQuery.getCity();
        Stream<UserQueryVO> stream = records.stream();
        // ID筛选
        if (!ObjectUtils.isEmpty(id)) {
            stream =  stream.filter(user ->  user.getId().equals(id));
        }
        // 名称模糊匹配
        if (!ObjectUtils.isEmpty(name)) {
            stream =  stream.filter(user ->  user.getName().contains(name));
        }
        // 年龄筛选
        if (!ObjectUtils.isEmpty(age)) {
            stream =  stream.filter(user -> age > 0 && age <= 120 && user.getAge().equals(age));
        }
        // 城市筛选，针对城市名称处理后缀问题
        if (!ObjectUtils.isEmpty(city)) {
            stream =  stream.filter(user ->  user.getCity().equals(city.endsWith("市") ? city : city.concat("市")));
        }
        // 按照ID排序后返回
        return stream.sorted(Comparator.comparing(UserQueryVO::getId)).collect(Collectors.toList());
    }


}
